/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package conversores;

import java.io.File;
import javax.el.ExpressionFactory;
import javax.el.ValueExpression;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;

/**
 *
 * @author Administrador
 */
@FacesConverter(value = "fichero")
public class ConversorFichero implements Converter {
    @Override
    public Object getAsObject(FacesContext context, UIComponent component, String value) {
        File f = new File("c:/" + value);
        if (f.exists()) {
            return f;
        } else {
            ExpressionFactory expressionFactory = context.getApplication().getExpressionFactory();
            ValueExpression ve = expressionFactory.createValueExpression(context.getELContext(), "#{i18n.noExiste}", String.class);
            String cadenaMensaje = (String) ve.getValue(context.getELContext());
            context.addMessage("fichero", new FacesMessage(cadenaMensaje));
            return f;
        }
    }

    @Override
    public String getAsString(FacesContext context, UIComponent component, Object value) {
        File f = (File) value;
        if (f == null) {
            return "";
        }
        return f.getAbsolutePath().substring(3);
    }
}
